#include "Slist.h"

slistnode* buyslistnode(slistdatatype x)
{
	slistnode* plst = (slistnode*)malloc(sizeof(slistdatatype));
	if (plst == NULL)
	{
		exit(-1);
	}
	plst->data = x;
	plst->next = NULL;
	return plst;
}

void slistprint(slistnode* plist)
{
	assert(plist);
	while (plist)
	{
		printf("%d->", plist->data);
		plist = plist->next;
	}
	printf("\n");
}

void slistpushback(slistnode** plist, slistdatatype x)
{
	if (*plist)
	{
		slistnode* head = *plist;
		while ((*plist)->next)
		{
			*plist = (*plist)->next;
		}
		(*plist)->next = buyslistnode(x);
		*plist = head;
	}
	else
	{
		*plist = buyslistnode(x);
	}

}

void slistpushfront(slistnode** plist, slistdatatype x)
{
	slistnode* next = *plist;
	slistnode* new = buyslistnode(x);
	new->next = next;
	*plist = new;
}


void slistpopfront(slistnode** plist)
{
	if (*plist)
	{
		slistnode* headnext = (*plist)->next;
		free(*plist);
		*plist = headnext;
	}
}


slistnode* slistfind(slistnode* plist, slistdatatype x)
{
	while (plist)
	{
		if (plist->data == x)
		{
			plist->next = NULL;
			return plist;
		}
		plist = plist->next;
	}
	return NULL;
}


void slistinsertafter(slistnode* pos, slistdatatype x)
{
	if (pos)
	{
		slistnode* posnext = pos->next;
		slistnode* new = buyslistnode(x);
		new->next = posnext;
		pos->next = new;
	}
}

void slistpopback(slistnode** plist)
{
	if (*plist)
	{
		slistnode* head = *plist;
		while (head->next->next)
		{
			head = head->next;
		}
		free(head->next);
		head->next = NULL;
	}
}

void slisteraseafter(slistnode* pos)
{
	slistnode* posnext = pos->next;
	pos->next = NULL;
	while (posnext)
	{
		slistnode* new = posnext->next;
		free(posnext);
		posnext = new;
	}
}

void slistdestroy(slistnode** plist)
{
	slistnode* next = (*plist)->next;
	while (next)
	{
		slistnode* nex = next->next;
		free(next);
		next = nex;
	}
	free(*plist);
	*plist = NULL;
}